package com.example.shior;

import com.example.entity.User;
import com.example.service.UserService;
import com.example.util.JwtUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * shiro 登录逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        // 获取 JwtToken
        JwtToken jwtToken = (JwtToken) authenticationToken;
        // 获取ID
        String userID = jwtUtils.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();
        System.out.println("ID:"+userID);
        // 查询
        User user = userService.getById(Long.valueOf(userID));
        // 判断用户状态
        if (user == null) {
            throw new UnknownAccountException("该用户不存在");
        }

        AccountProfile profile = new AccountProfile();
        BeanUtils.copyProperties(user, profile);

        // 返回
        return new SimpleAuthenticationInfo(profile, jwtToken.getCredentials(), getName());
    }
}
